#! /usr/bin/python
# - coding: utf-8 -*-

# Copyright (c) 2007-2008 Renato Chencarek. All rights reserved.
#
# Author: Renato Chencarek <renato.chencarek@gmail.com>
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import os
import time
from common import *

Log = None

def check_hd(name):
    if "720p" in name.lower():
        return True
    if "1080p" in name.lower():
        return True
    if "720i" in name.lower():
        return True
    if "1080i" in name.lower():
        return True

    return False

def run_ps3encoder(filename, out, mconf):
    global Log

    basename = os.path.basename(filename)
    basename = os.path.splitext(basename)[0]

    encoder_ld = mconf["ENCODER"]
    encoder_hd = mconf["ENCODER_HD"]

    if check_hd(filename):
        encoder = encoder_hd
    else:
        encoder = encoder_ld

    Log("%s %s %s" % (encoder, filename, os.path.join(out, basename + ".mp4")))
    os.system('%s "%s" "%s"' % (encoder, filename, os.path.join(out, basename + ".mp4")))

def is_encoder_running(mconf):
    return os.path.exists(mconf['PID_ENCODER'])

def run_encoder(path):
    os.spawnl(os.P_NOWAIT, "/usr/bin/encoder", "/usr/bin/encoder", "-U", path)

def encode_file(video, folder, mconf):
    global Log
    ext = os.path.splitext(video)[1].lower()

    if not ext in [".avi", ".mkv", ".mpg", ".mpeg", ".divx"]:
        Log("%s is not a valid media file" % video)
        return

    path = os.path.join(mconf['VIDEOS_DIR'], folder)

    if not os.path.exists(path):
        mkdirs(path)

    run_ps3encoder(video, path, mconf)

    change_owner(path, mconf['HOST_USER'])
    Log("Updating UPnP server: %s" % mconf['UPNP_UPDATE'])
    os.spawnl(os.P_NOWAIT, mconf['UPNP_UPDATE'], mconf['UPNP_UPDATE'], "", "")

def encode_dir(path, mconf):
    folder = os.path.basename(os.path.dirname(path + "/"))
    files = [os.path.join(path, f) for f in os.listdir(path)]

    for f in files:
        if os.path.isdir(f):
            videos_dir = mconf['VIDEOS_DIR']
            mconf['VIDEOS_DIR'] = os.path.join(mconf['VIDEOS_DIR'], folder)
            encode_dir(f, mconf)
            mconf['VIDEOS_DIR'] = videos_dir
        else:
            encode_file(f, folder, mconf)

def encoder(path, mconf, log = print_std):
    global Log

    Log = log

    if os.path.isdir(path):
        encode_dir(path, mconf)
    else:
        folder = os.path.splitext(os.path.basename(path))[0]
        encode_file(path, folder, mconf)


